import javax.swing.JPanel;

import javax.swing.border.LineBorder;

import org.json.JSONArray;
import org.json.JSONObject;

import java.awt.Color;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

import javax.swing.SwingConstants;
import javax.swing.JRadioButton;

import javax.swing.JFileChooser;

import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.awt.event.ActionEvent;
import javax.swing.ButtonGroup;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;

public class ImportData_Stu extends JPanel {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JTextField TF_dir;
	private JTextField TF_name;
	private JTextField TF_note;
	private JTextField TF_number;
	private JComboBox<String> CB_room;
	private final ButtonGroup buttonGroup = new ButtonGroup();
	private JPanel P_import_group;
	private JButton B_import_group;
	private JButton B_choose_dir;
	private JPanel P_import_one;
	private JButton B_import_one;
	private JLabel L_name;
	private JLabel L_sex;
	private JLabel L_room;
	private JLabel L_note;
	private JLabel L_number;
	private JRadioButton RB_boy;
	private JRadioButton RB_girl;


	/**
	 * Create the panel.
	 */
	public void updateComboBox(){
		String sendMsg = "{\"method\":\"show_room\",\"room_sex\":\""+(RB_boy.isSelected()?"boy":"girl")+"\",\"room_status\":\"avilable\"}";
		try{
			JSONObject obj = new JSONObject(new SocketOp().request(sendMsg));
			if(obj.has("result")){
				JSONArray arr = new JSONArray(obj.get("result").toString());
				CB_room.removeAllItems();
				CB_room.addItem("");
				for(int i=0;i<arr.length();i++){
					CB_room.addItem(arr.getString(i));
				}
			}
		}catch(Exception e){
			
		}
	}
	private boolean checkTextLengh(String text,int len,String Name){
		if(text.length()>len)
		{
			JOptionPane.showMessageDialog(null,Name+"不得超过"+len+"个字符",Name+"错误",JOptionPane.ERROR_MESSAGE);
			return false;
		}
		return true;
	}
	
	private boolean check_student(String str){
		try{
			JSONObject obj = new JSONObject(new SocketOp().request("{\"method\":\"get_student\",\"student_number\":\""+str+"\"}"));
			if(obj.has("student_number")&&obj.getString("student_number").equals(str)){
				return false;//已存在
			}else{
				return true;//不存在
			}
		}catch(Exception e){
			return true;//不存在
		}
		
	}
	private boolean check_file_name(String str){
		for(int i=0;i<str.length();i++)
		{
			if(Character.isDigit(str.charAt(i))){
				continue;
			}else{
				return false;
			}
		}
		if(str.charAt(0)=='0')
			return false;
		return true;
	}
	
	private void check_dir(String dirStr){
		int jsonFiles = 0;
		int importFiles = 0;
		try{
			File[] fs = new File(dirStr).listFiles();
			for(int i=0;i<fs.length;i++){
				try{
					if(fs[i].isFile()){
						String fileName = fs[i].getAbsolutePath();
						if(fileName.substring(fileName.lastIndexOf('.')+1).equals("json")){
							jsonFiles ++;
							if(new File(fileName).canRead()){
								BufferedReader in = new BufferedReader(new FileReader(fileName));
								String sendMsg = in.readLine();
								while(in.ready()){
									sendMsg += in.readLine();
								}
								JSONObject obj = new JSONObject(sendMsg);
								if(obj.has("student_name")&&obj.has("student_number")&&obj.has("student_sex")&&obj.has("student_room")&&obj.has("student_note")&&check_file_name(obj.getString("student_number"))&&check_student(obj.getString("student_number"))){
									obj.put("method", "import_student");
									if(new JSONObject(new SocketOp().request(obj.toString())).get("method").toString().equals("import_student")){
										importFiles++;
									}
								}
								
								in.close();
							}
						}
					}
				}catch(Exception e1){
					
				}
			}
		}catch(Exception e){
			
		}
		JOptionPane.showMessageDialog(null, "当期目录下共有JSON文件:"+jsonFiles+"个\n成功导入学生数据:"+importFiles+"个");
	}
	public ImportData_Stu() {

		setBorder(new LineBorder(Color.LIGHT_GRAY));
		setLayout(null);
		
		P_import_group = new JPanel();
		P_import_group.setLayout(null);
		P_import_group.setBorder(new LineBorder(Color.LIGHT_GRAY));
		P_import_group.setBounds(21, 192, 441, 144);
		add(P_import_group);
		
		TF_dir = new JTextField();
		TF_dir.setColumns(10);
		TF_dir.setBounds(10, 66, 306, 21);
		P_import_group.add(TF_dir);
		
		B_import_group = new JButton("批量导入");
		B_import_group.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(TF_dir.getText().equals(""))
					JOptionPane.showMessageDialog(null, "没有设置目录");
				else
					check_dir(TF_dir.getText());
			}
		});
		B_import_group.setBounds(175, 111, 93, 23);
		P_import_group.add(B_import_group);
		
		B_choose_dir = new JButton("选择文件夹");
		B_choose_dir.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JFileChooser jFileChooser = new JFileChooser();
				jFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
				jFileChooser.showOpenDialog(jFileChooser);
				try{
					TF_dir.setText(jFileChooser.getSelectedFile().getAbsolutePath());
				}catch(Exception e1){}
			}
		});
		B_choose_dir.setBounds(326, 65, 105, 23);
		P_import_group.add(B_choose_dir);
		
		P_import_one = new JPanel();
		P_import_one.setLayout(null);
		P_import_one.setBorder(new LineBorder(Color.LIGHT_GRAY));
		P_import_one.setBounds(21, 38, 441, 144);
		add(P_import_one);
		
		B_import_one = new JButton("单个导入");
		
		B_import_one.setBounds(173, 111, 93, 23);
		P_import_one.add(B_import_one);
		
		L_name = new JLabel("姓名");
		L_name.setHorizontalAlignment(SwingConstants.RIGHT);
		L_name.setBounds(10, 10, 54, 15);
		P_import_one.add(L_name);
		
		L_sex = new JLabel("性别");
		L_sex.setHorizontalAlignment(SwingConstants.RIGHT);
		L_sex.setBounds(10, 35, 54, 15);
		P_import_one.add(L_sex);
		
		L_room = new JLabel("宿舍");
		L_room.setHorizontalAlignment(SwingConstants.RIGHT);
		L_room.setBounds(197, 35, 54, 15);
		P_import_one.add(L_room);
		
		L_note = new JLabel("备注");
		L_note.setHorizontalAlignment(SwingConstants.RIGHT);
		L_note.setBounds(10, 60, 54, 15);
		P_import_one.add(L_note);
		
		L_number = new JLabel("学号");
		L_number.setHorizontalAlignment(SwingConstants.RIGHT);
		L_number.setBounds(197, 10, 54, 15);
		P_import_one.add(L_number);
		
		TF_name = new JTextField();
		TF_name.setBounds(74, 7, 113, 21);
		P_import_one.add(TF_name);
		TF_name.setColumns(10);
		
		RB_boy = new JRadioButton("男");
		RB_boy.setSelected(true);
		buttonGroup.add(RB_boy);
		RB_boy.setBounds(74, 31, 54, 23);
		P_import_one.add(RB_boy);
		
		RB_girl = new JRadioButton("女");
		buttonGroup.add(RB_girl);
		RB_girl.setBounds(130, 31, 54, 23);
		P_import_one.add(RB_girl);
		
		TF_note = new JTextField();
		TF_note.setBounds(74, 57, 303, 21);
		P_import_one.add(TF_note);
		TF_note.setColumns(10);
		
		TF_number = new JTextField();
		TF_number.setBounds(261, 7, 116, 21);
		P_import_one.add(TF_number);
		TF_number.setColumns(10);
		
		CB_room = new JComboBox<String>();
		CB_room.setModel(new DefaultComboBoxModel<String>());
		CB_room.removeAllItems();
		CB_room.setBounds(261, 32, 116, 21);
		
		P_import_one.add(CB_room);

		RB_girl.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				updateComboBox();
			}
		});
		RB_boy.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				updateComboBox();
			}
		});




		B_import_one.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(TF_name.getText().equals("")){
					JOptionPane.showMessageDialog(null, "姓名不得为空", "姓名错误", JOptionPane.ERROR_MESSAGE);
					return ;
				}
				if(!checkTextLengh(TF_name.getText(),20,"姓名")){
					return;
				}else if(!check_file_name(TF_number.getText())){
					JOptionPane.showMessageDialog(null, "学号需为不已0开头的12位数字","导入失败",JOptionPane.ERROR_MESSAGE);
					return;
				}else if(!check_student(TF_number.getText())){
					JOptionPane.showMessageDialog(null, "当前学生的学号已经被占用，请核对学号姓名是否有误","导入失败",JOptionPane.ERROR_MESSAGE);
					return;
				}else if(!checkTextLengh(TF_note.getText(),200,"备注")){
					return;
				}
				
				
				String sendMsg = "{\"method\":\"import_student\",\"student_name\":\""+TF_name.getText()+"\",\"student_number\":\""+TF_number.getText()+"\",\"student_sex\":\""+(RB_boy.isSelected()?"boy":"girl")+"\",\"student_room\":\""+CB_room.getSelectedItem()+"\",\"student_note\":\""+TF_note.getText()+"\"}";
				try{
//					String tmp = new SocketOp().request(sendMsg);
//					JOptionPane.showMessageDialog(null, tmp);
					JSONObject obj = new JSONObject(new SocketOp().request(sendMsg));
					if(obj.has("result")&&obj.getString("result").equals("success")){
						JOptionPane.showMessageDialog(null, "导入成功");
						
					}else{
						JOptionPane.showMessageDialog(null, "导入失败","错误",JOptionPane.ERROR_MESSAGE);
					}
				}catch(Exception e1){
					JOptionPane.showMessageDialog(null, "系统错误，错误代码：0100");
				}
			}
		});

	}
}
